/**
 * Created with IntelliJ IDEA.
 * User: aleksandr
 * Date: 12.07.13
 */
package com.google.code.bankagregator.ui;

import com.google.code.bankagregator.core.UpdateManager;
import com.google.code.bankagregator.dao.ScheduleDAO;
import com.google.code.bankagregator.entities.ScheduleEntity;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

@WebServlet(name = "AdminServlet", urlPatterns = {"/adminarea"})
public class AdminServlet extends HttpServlet {

    private final Logger log = Logger.getLogger(AdminServlet.class.getName());
    @EJB
    UpdateManager updateManager;
    @EJB
    ScheduleDAO scheduleDAO;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (request.getParameter("renew") != null) {
            String renew = request.getParameter("renew");
            if ("all".equals(renew)) {
                log.log(Level.INFO, "Manual update running at " + new Date().toString());
                updateManager.updateProducts();
            }
        }

        if (request.getParameter("schedule") != null) {
            ScheduleEntity scheduleEntity = new ScheduleEntity();
            scheduleEntity.setParamName("scheduletime");
            scheduleEntity.setParamValue(request.getParameter("schedule"));
            scheduleDAO.update(scheduleEntity);
        }

        ScheduleEntity scheduleEntity = scheduleDAO.read("scheduletime");
        String scheduleValue = null;
        if (scheduleEntity == null) {
            scheduleValue = "";
        } else {
            scheduleValue = scheduleEntity.getParamValue();
        }
        request.setAttribute("scheduleperiod", scheduleValue);
        request.getRequestDispatcher("adminpanel.jspx").forward(request, response);
    }
}
